import axios from 'axios'
import Cookies from 'js-cookie'
import { tokenKey } from './constant'

class HttpRequest {
  constructor(baseUrl) {
    this.baseUrl = baseUrl;
    this.queue = {}
  }
  getInsideConfig () {
    let token = Cookies.get(tokenKey);
    const config = {
      baseURL: this.baseUrl,
      headers: {
        Authorization: token || 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ3ZW5jaGVuZyIsImV4cCI6MTU3ODgzNzI4OCwiaWF0IjoxNTc4MjMyNDg4fQ.HmCYrqUeWXuJUQGCqrD7oTc-GEgjiQgpipRnHFHxo5Q0wfyqorr6X_pyhVJ91gBxFZNEN_YTH2zUJOEvzoL-SA'
      }
    };
    return config
  }
  destroy (url) {
    delete this.queue[url];
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true;
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url);
      const { data, status } = res;
      return { data, status }
    }, error => {
      this.destroy(url);
      let errorInfo = error.response;
      if (!errorInfo) {
        const { request: { statusText, status }, config } = JSON.parse(JSON.stringify(error));
        errorInfo = {
          statusText,
          status,
          request: { responseURL: config.url }
        }
      }
      // 拒绝原因
      return Promise.reject(error)
    })
  }
  request (options) {
    const instance = axios.create();
    options = Object.assign(this.getInsideConfig(), options);
    this.interceptors(instance, options.url);
    return instance(options)
  }
}
export default HttpRequest
